package com.example.demo.conteoller;


import com.example.demo.mdoel.User;
import com.example.demo.service.RedisService;
import com.example.demo.utils.PasswordUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final RedisService redisService;

    public AuthController(RedisService redisService) {
        this.redisService = redisService;
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody User user) {
        if (redisService.userExists(user.getUsername())) {
            return ResponseEntity.badRequest().body("用户名已存在");
        }

        String hashedPass = PasswordUtil.hashPassword(user.getPassword());
        user.setPassword(hashedPass);

        redisService.saveUser(user);

        return ResponseEntity.ok("注册成功！");
    }

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody User user) {
        User storedUser = redisService.getUserByUsername(user.getUsername());

        if (storedUser == null || !PasswordUtil.checkPassword(user.getPassword(), storedUser.getPassword())) {
            return ResponseEntity.status(401).body("用户名或密码错误");
        }

        String token = "token_" + System.currentTimeMillis();  // 模拟 Token
        return ResponseEntity.ok(token);
    }
}